import * as multer from 'koa-multer';
import {join, dirname} from 'path';
import * as fs from 'fs';
import {MW_PREFIX} from "../constants";


function mkdirs(dirpath) {
    if (!fs.existsSync(dirname(dirpath))) {
        mkdirs(dirname(dirpath));
    }
    fs.mkdirSync(dirpath);
}

export const Multer = (path: string = '') => function (target, name, descriptor: TypedPropertyDescriptor<any>) {

    let uploadPahtName = 'uploads/';
    if (path) {
        uploadPahtName = uploadPahtName + path;
    }

    const storage = multer.diskStorage({
        destination: (req, file, cb) => {
            let uploadDirPath = `public/${uploadPahtName}/${new Date().getFullYear()}${new Date().getMonth()}${new Date().getDay()}`;
            if (!fs.existsSync(uploadDirPath)) {
                mkdirs(uploadDirPath);
            }

            cb(null, uploadDirPath);
        },
        filename(req, file, cb) {
            const fileFormat = (file.originalname).split(".");
            cb(null, Date.now() + '.' + fileFormat[fileFormat.length - 1]);
        }
    });

    let upload = multer({storage: storage});

    if (!name) {
        name = '';
    } else {
        name = '_' + name;
    }
    Reflect.defineMetadata(`${MW_PREFIX}${name}`, [upload.single('file')], target);
};


